/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-17
 * Time: 19:21
 */
public class MyBlockinqueue {
    private String[] data;
    private static Object locker = new Object();
    private int head;
    private int tail;
    private int size;
    public MyBlockinqueue(int capacity){
        if(capacity <= 0){
            System.out.println("申请开辟空间范围小于等于0!");
            return;
        }
        data = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (locker){
            while(size == data.length){
                locker.wait();
            }
            data[tail] = elem;
            tail++;
            size++;
            if(tail >= data.length){
                tail = 0;
            }
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (locker){
            while(size == 0){
                locker.wait();
            }
            String ret = data[head];
            head++;
            size--;
            if(head >= data.length){
                head = 0;
            }
            locker.notify();
            return ret;
        }
    }

    public static void main(String[] args) {
        MyBlockinqueue myBlockinqueue = new MyBlockinqueue(10);
        for(int i = 0; i < 30; i++){
            Thread t = new Thread(()->{
                try {
                    myBlockinqueue.put("hehe");
                    Thread.sleep(1000);
                    String ret = myBlockinqueue.take();
                    System.out.println(ret);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }

}
